/**
 * Created by tongjunshui on 17/6/9.
 */
var express = require('express');
var router = express.Router();


var settings = require('../../settings');

/**
 主页面.
 url:"/"
 请求方式:GET
 @method  _WxMenuEditPage
 @param req
 @param res
 @return 跳转到:/wxmp/weixinMenuEditView.html
 @private
 */

router.get('/', function (req,res){
    res.render('./wxpm/weixinMenuEditView.html', {
        locals: {
            title: settings.title,
            appid:settings.appid,
            secret:settings.secret,
        }
    });
})

/**
 向微信公众平台进行菜单操作.
 url:"/m/wx/menu/edit"
 请求方式:POST
 @method  _WxMenuEdit
 @param req
 @param res
 @return
 @private
 */

router.post('/', function (req,res){
    var menu = req.query.menuBody;
    var appid = req.query.appid;
    var secret = req.query.secret;

    var menu3 = '{' +
        '"button":[' +
        '{"name":"订场服务","type":"view", "name": "订场服务", "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + settings.appid + '&redirect_uri=http%3a%2f%2fgo.sportscv.cn&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"},' +
        '{"name":"我的账户","type":"view", "name": "我的账户", "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + settings.appid + '&redirect_uri=http%3a%2f%2fgo.sportscv.cn%2f#myaccount&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"}]}' +

        '{"type":"click","name":"b","key":"Ch02_CGAL"},' + //多余数据,保证数据长度正确
        ']' +
        '}';

    //取得access_token
    var tokenparam = "?grant_type=client_credential&appid="+appid+ "&secret=" +secret;

    console.log(tokenparam);
    var options = {
        hostname: 'api.weixin.qq.com',
        port: 443,
        path: '/cgi-bin/token' + tokenparam,
        //data: fqmenu1,
        method: 'GET',
        headers: {
            //'Content-Type': 'text/html',//'application/x-www-form-urlencoded',
            //'Content-Length': token.length + menus.length +6
            'Content-Length': tokenparam.length
        }
    };
    console.log('222---');
    var serareq = https.request(options, function(serares) {
        //log.logger.info('STATUS: ' + serares.statusCode);
        //log.logger.info('HEADERS: ' + JSON.stringify(serares.headers));
        serares.setEncoding('utf8');
        serares.on('data', function(respData) {
            var obj = eval("(" + respData + ")");
            console.log(obj.access_token);

            //统计有多少个汉字
            var gblen = countGb2312(menu3);

            if (req.param("menuType") == "创建菜单") {
                var tmp = '/cgi-bin/menu/create' + token;
                var len = tmp.length;
                var token = "?access_token=" + obj.access_token;
                var options = {
                    hostname: 'api.weixin.qq.com',
                    port: 443,
                    path: '/cgi-bin/menu/create' + token,
                    data: menu3,
                    method: 'POST',
                    headers: {
                        //'Content-Type': 'text/html',//'application/x-www-form-urlencoded',
                        'Content-Type': 'application/json; charset=UTF-8',
                        'Content-Length': menu3.length + gblen * 2
                    }
                };
                var serareq = https.request(options, function(serares) {
                    log.logger.info('STATUS: ' + serares.statusCode);
                    log.logger.info('HEADERS: ' + JSON.stringify(serares.headers));
                    serares.setEncoding('utf8');
                    serares.on('data', function(respData) {
                        console.log('rec Data=========================:\r\n' + respData);
                        //console.log('rec Data=========================:\r\n' + respData.errcode);
                        res.send(respData);
                    });
                });
                console.log('============' + menu3);
                log.logger.info("Send menu packageData!!!!!!!!!!!!!!!!");
                serareq.write(menu3);
                serareq.end();
            } else if (req.param("menuType") == "菜单查询") {
                console.log("菜单查询")
                var token = "?access_token=" + obj.access_token;
                var options = {
                    hostname: 'api.weixin.qq.com',
                    port: 443,
                    path: '/cgi-bin/menu/get' + token,
                    //data: menu,
                    method: 'GET',
                    headers: {
                        'Content-Type': 'text/html', //'application/x-www-form-urlencoded',
                        //'Content-Length': token.length + menus.length +6
                        //'Content-Length':  menu.length + len
                    }
                };
                var serareq = https.request(options, function(serares) {
                    log.logger.info('STATUS: ' + serares.statusCode);
                    log.logger.info('HEADERS: ' + JSON.stringify(serares.headers));
                    serares.setEncoding('utf8');
                    serares.on('data', function(respData) {
                        console.log('rec Data=========================:\r\n' + respData);
                        //console.log('rec Data=========================:\r\n' + respData.errcode);
                        res.send(respData);
                    });
                });
                console.log('============' + menu);
                log.logger.info("Send menu packageData!!!!!!!!!!!!!!!!");
                serareq.write(menu);
                serareq.end();
            }

        });
    });
    log.logger.info("Send  token packageData!!!!!!!!!!!!!!!!");
    serareq.write(tokenparam);
    serareq.end();


});


//统计有多少个汉字
function countGb2312(str) {
    var count = 0;
    for (var i = 0; i < str.length; i++) {
        var code = str.charCodeAt(i);
        //console.log('countGb2312 code=' + code)
        //if(code >= 19968 && code <= 40869) {
        if (code >= 11968 && code <= 80869) {
            count++;
        }
    }
    return count;
}

module.exports = router;